package com.atguigu.gulimall.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.ProductFeignService;
import com.atguigu.gulimall.auth.interceptor.CartInterceptor;
import com.atguigu.gulimall.auth.service.CartService;
import com.atguigu.gulimall.auth.to.UserInfoTO;
import com.atguigu.gulimall.auth.vo.Cart;
import com.atguigu.gulimall.auth.vo.CartItem;
import com.atguigu.gulimall.auth.vo.SkuInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    ThreadPoolExecutor executor;

    private final String CART_PREFIX = "gulimall:cart:";

    @Override
    public CartItem addToCart(Long skuId, Integer num){
        BoundHashOperations<String, Object, Object> operations = getCartOps();

        //检查购物车是否存在相同商品
        String res = (String) operations.get(skuId.toString());
        if (StringUtils.isEmpty(res)) {
            //没有相同商品，将商品添加到购物车
            CartItem cartItem = new CartItem();
            //异步编排
            //远程查询当前要添加的商品信息
            CompletableFuture<Void> skuInfoTask = CompletableFuture.runAsync(() -> {
                R skuInfo = productFeignService.getInfo(skuId);
                SkuInfoVO data = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVO>() {
                });
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(data.getSkuDefaultImg());
                cartItem.setTitle(data.getSkuTitle());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(data.getPrice());
            }, executor);

            //远程查询sku的组合信息
            CompletableFuture<Void> skuSaleAttrValueTask = CompletableFuture.runAsync(() -> {
                List<String> values = productFeignService.getSkuSaleAttrValuesAsStringList(skuId);
                cartItem.setSkuAttr(values);
            }, executor);

            //等待异步任务执行完成
            try {
                CompletableFuture.allOf(skuInfoTask, skuSaleAttrValueTask).get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }

            String s = JSON.toJSONString(cartItem);
            operations.put(skuId.toString(), s);
            return cartItem;
        } else {
           //有相同商品，修改数量
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount()+num);
            operations.put(skuId.toString(),JSON.toJSONString(cartItem));
            return cartItem;
        }

    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String s = (String) cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(s, CartItem.class);
        return cartItem;
    }

    @Override
    public Cart getCart() {
        Cart cart = new Cart();
        UserInfoTO userInfoTO = CartInterceptor.threadLocal.get();
        if (userInfoTO.getUserId() == null) {
            //没登陆
            String cartKey = CART_PREFIX + userInfoTO.getUserKey();
            //获取临时购物车数据
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        } else {
            //已登录
            String cartKey = CART_PREFIX + userInfoTO.getUserId();
            //判读临时购物车是否有数据，有则合并再删除临时数据
            String tempCartKey = CART_PREFIX + userInfoTO.getUserKey();
            List<CartItem> tempCartItems = getCartItems(tempCartKey);
            if (tempCartItems != null) {
                for (CartItem tempCartItem : tempCartItems) {
                    addToCart(tempCartItem.getSkuId(), tempCartItem.getCount());
                }
                //删除临时数据
                clearCart(tempCartKey);
            }
            //获取合并后的数据
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }
        return cart;
    }

    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        //修改数据
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        //更新缓存数据
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        //更新缓存数据
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTO userInfoTO = CartInterceptor.threadLocal.get();
        if (userInfoTO == null) {
            return null;
        }
        //获取当前用户的购物车数据
        List<CartItem> cartItems = getCartItems(CART_PREFIX + userInfoTO.getUserId());
        //获取被选中的购物项，并更新价格（缓存里的数据可能是一个月前的，价格可能已更新）
        return cartItems.stream().filter(item -> item.getCheck()).map(item -> {
            BigDecimal price = productFeignService.getPrice(item.getSkuId()).getData(new TypeReference<BigDecimal>(){});
            item.setPrice(price);
            return item;
        }).collect(Collectors.toList());
    }

    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (values != null && !values.isEmpty()) {
            List<CartItem> collect = values.stream().map(obj -> JSON.parseObject((String) obj, CartItem.class)).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    private BoundHashOperations<String, Object, Object>  getCartOps() {
        UserInfoTO userInfoTO = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoTO.getUserId() != null) {
            cartKey = CART_PREFIX + userInfoTO.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTO.getUserKey();
        }
        //绑定一个hash操作
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }
}
